package com.example.element.module.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActServiceBinding

class ServiceActivity : AbsActivity<ActServiceBinding>() {

    lateinit var downloadBinder: MyService.DownloadBinder

    //创建ServiceConnection匿名实现类
    private val connection= object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            //创建进程崩溃、被杀死的时候调用
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            //绑定的时候调用
            downloadBinder = service as MyService.DownloadBinder
            downloadBinder.startDownload()
            downloadBinder.getProgress()
        }

    }

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, ServiceActivity::class.java))
        }
    }

    override fun getLayoutId() = R.layout.act_service;

    override fun main() {

    }

    override fun initListener() {
        mBinding.btnStartService.setOnClickListener {
            val intent = Intent(mContext, MyService::class.java)
            startService(intent)
        }

        mBinding.btnStopService.setOnClickListener {
            val intent = Intent(mContext, MyService::class.java)
            stopService(intent)
        }

        mBinding.btnBindService.setOnClickListener {
            //绑定service
            val intent = Intent(this, MyService::class.java)
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }

        mBinding.btnUnBindService.setOnClickListener {
            //解绑Service
            unbindService(connection)
        }

        mBinding.btnForeGService.setOnClickListener {
            val intent = Intent(mContext, ForegroundService::class.java)
            startService(intent)
        }

        mBinding.btnStopForeGService.setOnClickListener {
            val intent = Intent(mContext, ForegroundService::class.java)
            stopService(intent)
        }
    }

}